package com.bluesky.light2.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bluesky.light2.model.User;

@Component("userService")
public class UserService {
	private HibernateTemplate hibernateTemplate;
	
	public void add(User u) {
		u.setRdate(new Date());
		hibernateTemplate.save(u);
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public List<User> getUsers() {
		return this.hibernateTemplate.find("from User");
	}

	public void deleteById(int id) {
		User u = new User();
		u.setId(id);
		this.hibernateTemplate.delete(u);
	}

	public User loadById(int id) {
		return (User)this.hibernateTemplate.get(User.class, id);
	}

	public void updateInfo(User user) {
		Object[] values = {user.getName(), user.getIdcard(), user.getSex(), user.getAge(), user.getPhone(), user.getAddr(), user.getId()};
		this.hibernateTemplate
			.bulkUpdate("update User u set u.name = ?, u.idcard = ?, u.sex = ?" 
			+ ", u.age = ?, u.phone = ?, u.addr = ? where u.id = ?", values);
	}

	public void updatePassword(User user) {
		Object[] values = {user.getPassword(), user.getId()};
		this.hibernateTemplate.bulkUpdate("update User u set u.password = ? where u.id = ?", values);
	}

	public User loadByUsername(String username) {
		User u = null;
		List<User> users = (List<User>)this.hibernateTemplate.find("from User u where u.username = ?", username);
		if (users.size() != 0) {
			u = users.get(0);
		}
		return u;
	}
}
